package com.ttcaca.cas.android.client.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.tsz.afinal.core.AsyncTask;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.webkit.WebView;
import android.widget.Toast;

import com.boyuan.huijiaoyu.ColorHolderApplication;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.magicsoft.app.wcf.AsyncHttpServiceHelper;
import com.magicsoft.app.wcf.listener.PostRecordResponseListener;
import com.magicsoft.constant.Constant;

public class Helper {

	private static String postUrl;
	private static RequestParams uploadParams;
	private static Context mContext;
	private static int TYPE_PDF = 0;
	private static int TYPE_AUDIO = 1;
	private static int TYPE_VIDEO = 2;
	private static int TYPE_IMAGE = 3;
	private static int TYPE_APP = 4;
	private static int TYPE_OTHERS = 9;
	private static ColorHolderApplication app = ColorHolderApplication
			.getInstance();

	public static void setContext(Context context) {
		mContext = context;
	}

	public static RequestParams getParams(JSONObject jsonObject)
			throws JSONException {
		RequestParams requestParams = new RequestParams();
		Iterator iterator = jsonObject.keys();
		String key = null;
		String value = null;
		while (iterator.hasNext()) {
			key = (String) iterator.next();
			value = jsonObject.getString(key);
			requestParams.put(key, value);
		}
		return requestParams;
	}

	@SuppressLint("NewApi")
	public static String getFileAbsolutePath(Activity context, Uri fileUri) {
		if (context == null || fileUri == null)
			return null;
		if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT
				&& DocumentsContract.isDocumentUri(context, fileUri)) {
			if (isExternalStorageDocument(fileUri)) {
				String docId = DocumentsContract.getDocumentId(fileUri);
				String[] split = docId.split(":");
				String type = split[0];
				if ("primary".equalsIgnoreCase(type)) {
					return Environment.getExternalStorageDirectory() + "/"
							+ split[1];
				}
			} else if (isDownloadsDocument(fileUri)) {
				String id = DocumentsContract.getDocumentId(fileUri);
				Uri contentUri = ContentUris.withAppendedId(
						Uri.parse("content://downloads/public_downloads"),
						Long.valueOf(id));
				return getDataColumn(context, contentUri, null, null);
			} else if (isMediaDocument(fileUri)) {
				String docId = DocumentsContract.getDocumentId(fileUri);
				String[] split = docId.split(":");
				String type = split[0];
				Uri contentUri = null;
				if ("image".equals(type)) {
					contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
				} else if ("video".equals(type)) {
					contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
				} else if ("audio".equals(type)) {
					contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
				}
				String selection = MediaStore.Images.Media._ID + "=?";
				String[] selectionArgs = new String[] { split[1] };
				return getDataColumn(context, contentUri, selection,
						selectionArgs);
			}
		} // MediaStore (and general)
		else if ("content".equalsIgnoreCase(fileUri.getScheme())) {
			// Return the remote address
			if (isGooglePhotosUri(fileUri))
				return fileUri.getLastPathSegment();
			return getDataColumn(context, fileUri, null, null);
		}
		// File
		else if ("file".equalsIgnoreCase(fileUri.getScheme())) {
			return fileUri.getPath();
		}
		return null;
	}

	public static String getDataColumn(Context context, Uri uri,
			String selection, String[] selectionArgs) {
		Cursor cursor = null;
		String column = MediaStore.Images.Media.DATA;
		String[] projection = { column };
		try {
			cursor = context.getContentResolver().query(uri, projection,
					selection, selectionArgs, null);
			if (cursor != null && cursor.moveToFirst()) {
				int index = cursor.getColumnIndexOrThrow(column);
				return cursor.getString(index);
			}
		} finally {
			if (cursor != null)
				cursor.close();
		}
		return null;
	}

	/**
	 * @param uri
	 *            The Uri to check.
	 * @return Whether the Uri authority is ExternalStorageProvider.
	 */
	public static boolean isExternalStorageDocument(Uri uri) {
		return "com.android.externalstorage.documents".equals(uri
				.getAuthority());
	}

	/**
	 * @param uri
	 *            The Uri to check.
	 * @return Whether the Uri authority is DownloadsProvider.
	 */
	public static boolean isDownloadsDocument(Uri uri) {
		return "com.android.providers.downloads.documents".equals(uri
				.getAuthority());
	}

	/**
	 * @param uri
	 *            The Uri to check.
	 * @return Whether the Uri authority is MediaProvider.
	 */
	public static boolean isMediaDocument(Uri uri) {
		return "com.android.providers.media.documents".equals(uri
				.getAuthority());
	}

	/**
	 * @param uri
	 *            The Uri to check.
	 * @return Whether the Uri authority is Google Photos.
	 */
	public static boolean isGooglePhotosUri(Uri uri) {
		return "com.google.android.apps.photos.content".equals(uri
				.getAuthority());
	}

	public static void uploadFile(String url, String case_id, String file_name,
			String operator_id, String operator, File file,
			final PostRecordResponseListener listener) {
		RequestParams requestParams = new RequestParams();
		requestParams.put("case_id", case_id);
		requestParams.put("operator_id", operator_id);
		requestParams.put("operator", operator);
		requestParams.put("file_name", file_name);
		try {
			requestParams.put("file", file);
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}
		AsyncHttpServiceHelper.post(url, requestParams,
				new JsonHttpResponseHandler() {
					@Override
					public void onSuccess(int statusCode, Header[] headers,
							JSONObject response) {
						Log.e("response", response.toString());
						super.onSuccess(statusCode, headers, response);
						try {
							String code = response.getString("result");
							String message = response.getString("message");
							if ("0".equals(code)) {
								if (listener != null) {
									listener.onFinish(message);
								}
							} else {
								if (listener != null) {
									listener.onFailed(message);
								}
							}
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							Throwable throwable, JSONObject errorResponse) {
						Log.e("11111", errorResponse.toString());
						if(listener != null){
							listener.onFailed("");
						}
						super.onFailure(statusCode, headers, throwable,
								errorResponse);
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							String responseString, Throwable throwable) {
						Log.e("22222", responseString);
						if(listener != null){
							listener.onFailed("");
						}
						super.onFailure(statusCode, headers, responseString,
								throwable);
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							Throwable throwable, JSONArray errorResponse) {
						Log.e("33333", errorResponse.toString());
						if(listener != null){
							listener.onFailed("");
						}
						super.onFailure(statusCode, headers, throwable,
								errorResponse);
					}
				});
	}

	public static void uploadFile(String FILE_NAME, final WebView webView) {
		File file = new File(FILE_NAME);
		try {
			uploadParams.put("file", file);
		} catch (FileNotFoundException e) {
			Log.e("catch", "FileNotFoundException:" + e.toString());
			e.printStackTrace();
		}
		AsyncHttpClient httpClient = new AsyncHttpClient();
		httpClient.setTimeout(15 * 1000);
		httpClient.post(postUrl, uploadParams, new AsyncHttpResponseHandler() {

			@Override
			public void onStart() {
				super.onStart();
			}

			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2,
					Throwable arg3) {
				showToast(mContext, "连接失败，请检查网络或联系管理员！");
			}

			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				String result = null;
				try {
					result = new String(arg2, "UTF-8");
					result = replaceBlank(result);
					JSONObject jsonObject = new JSONObject(result);
					String cons = jsonObject.getString("result");
					if (!cons.equals("success")) {
						String msg = jsonObject.getString("message");
						msg = unicode2Utf8(msg);
						showToast(mContext, "上传失败！\n" + msg);
					} else {
						showToast(mContext, "上传成功！");
					}
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				} catch (JSONException e) {
					e.printStackTrace();
				} catch (Exception e) {
				}

				webView.loadUrl("javascript:uploadCallback('" + result + "')");
			}
		});
	}

	public static void setParams(String json) {
		try {
			JSONObject jsonObject = new JSONObject(json);
			postUrl = jsonObject.getString("url");
			uploadParams = getParams(jsonObject.getJSONObject("params"));
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	public static String replaceBlank(String str) {
		String dest = "";
		if (str != null) {
			Pattern p = Pattern.compile("\\s*|\t|\r|\n");
			Matcher m = p.matcher(str);
			dest = m.replaceAll("");
		}
		return dest;
	}

	public static Intent getFileIntent(File file) {
		Uri uri = Uri.fromFile(file);
		String type = getFileType(file);
		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setDataAndType(uri, type);
		return intent;
	}

	public static String getFileType(File f) {
		String type = "";
		String fName = f.getName();
		/* 取得扩展名 */
		String end = fName
				.substring(fName.lastIndexOf(".") + 1, fName.length())
				.toLowerCase();

		/* 依扩展名的类型决定MimeType */
		if (end.equals("pdf")) {
			type = "application/pdf";//
		} else if (end.equals("m4a") || end.equals("mp3") || end.equals("mid")
				|| end.equals("xmf") || end.equals("ogg") || end.equals("wav")) {
			type = "audio/*";
		} else if (end.equals("3gp") || end.equals("mp4")) {
			type = "video/*";
		} else if (end.equals("jpg") || end.equals("gif") || end.equals("png")
				|| end.equals("jpeg") || end.equals("bmp")) {
			type = "image/*";
		} else if (end.equals("apk")) {
			/* android.permission.INSTALL_PACKAGES */
			type = "application/vnd.android.package-archive";
		} else {
			// /*如果无法直接打开，就跳出软件列表给用户选择 */
			type = "*/*";
		}
		return type;
	}

	public static int getFileIntType(File f) {
		String type = getFileType(f);
		if (type.equals("application/pdf")) {
			return TYPE_PDF;
		} else if (type.equals("audio/*")) {
			return TYPE_AUDIO;
		} else if (type.equals("video/*")) {
			return TYPE_VIDEO;
		} else if (type.equals("image/*")) {
			return TYPE_IMAGE;
		} else if (type.equals("application/vnd.android.package-archive")) {
			return TYPE_APP;
		} else if (type.equals("*/*")) {
			return TYPE_OTHERS;
		}
		return 0;
	}

	public static void writeToDownload(String fileName, InputStream input) {

		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			File directory = new File(Constant.DOWNLOAD_DIRECT);
			if (!directory.exists()) {
				directory.mkdirs();
			}
			String newFile = directory + "/" + getNewName(fileName, 1);
			File file = new File(newFile);
			if (!file.exists()) {
				try {
					file.createNewFile();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			try {
				FileOutputStream fos = new FileOutputStream(file);
				byte[] b = new byte[2048];
				int j = 0;
				while ((j = input.read(b)) != -1) {
					fos.write(b, 0, j);
				}
				fos.flush();
				fos.close();
			} catch (FileNotFoundException e) {
				Log.e("tag", "FileNotFoundException:" + e.getMessage());
				e.printStackTrace();
			} catch (IOException e) {
				Log.e("tag", "IOException:" + e.getMessage());
				e.printStackTrace();
			}
		} else {
			Log.e("tag", "NO SDCard.");
		}
	}

	private static String getNewName(String fileName, int i) {
		// String end = fileName.substring(fileName.lastIndexOf(".") + 1)
		// .toLowerCase();
		// String name = fileName.substring(0, fileName.lastIndexOf("."));
		// String newFile = name + "(" + i + ")." + end;
		// File directory = new File(Constant.DOWNLOAD_DIRECT);
		// File f = new File(directory + "/" + newFile);
		// if (f.exists()) {
		// i++;
		// return getNewName(fileName, i);
		// } else {
		// return newFile;
		// }
		String end = fileName.substring(fileName.lastIndexOf(".") + 1)
				.toLowerCase();
		String name = fileName.substring(0, fileName.lastIndexOf("."));
		if (1 == i) {
			return name + "." + end;
		}
		String newFile = name + "(" + i + ")." + end;
		File directory = new File(Constant.DOWNLOAD_DIRECT);
		File f = new File(directory + newFile);
		if (f.exists()) {
			i++;
			return getNewName(fileName, i);
		} else {
			return newFile;
		}
	}

	public static String getReallyFileName(String url) {
		String filename = "";
		URL myURL;
		HttpURLConnection conn = null;
		if (url == null || url.length() < 1) {
			return null;
		}

		try {
			myURL = new URL(url);
			conn = (HttpURLConnection) myURL.openConnection();
			conn.connect();
			conn.getResponseCode();
			URL absUrl = conn.getURL();// 获得真实Url
			filename = conn.getHeaderField("Content-Disposition");// 通过Content-Disposition获取文件名，这点跟服务器有关，需要灵活变通
			if (filename == null || filename.length() < 1) {
				filename = absUrl.getFile();
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (conn != null) {
				conn.disconnect();
				conn = null;
			}
		}

		return filename;
	}

	private static Toast toast;

	public static void showToast(Context context, String msg) {
		// Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
		if (toast == null) {
			toast = Toast.makeText(context, msg, Toast.LENGTH_SHORT);
			toast.setGravity(Gravity.CENTER, 0, 0);
		}
		toast.setText(msg);
		toast.show();
	}

	/**
	 * unicode 转换成 utf-8
	 * 
	 * @param theString
	 * @return
	 */
	public static String unicode2Utf8(String theString) {
		char aChar;
		int len = theString.length();
		StringBuffer outBuffer = new StringBuffer(len);
		for (int x = 0; x < len;) {
			aChar = theString.charAt(x++);
			if (aChar == '\\') {
				aChar = theString.charAt(x++);
				if (aChar == 'u') {
					// Read the xxxx
					int value = 0;
					for (int i = 0; i < 4; i++) {
						aChar = theString.charAt(x++);
						switch (aChar) {
						case '0':
						case '1':
						case '2':
						case '3':
						case '4':
						case '5':
						case '6':
						case '7':
						case '8':
						case '9':
							value = (value << 4) + aChar - '0';
							break;
						case 'a':
						case 'b':
						case 'c':
						case 'd':
						case 'e':
						case 'f':
							value = (value << 4) + 10 + aChar - 'a';
							break;
						case 'A':
						case 'B':
						case 'C':
						case 'D':
						case 'E':
						case 'F':
							value = (value << 4) + 10 + aChar - 'A';
							break;
						default:
							throw new IllegalArgumentException(
									"Malformed   \\uxxxx   encoding.");
						}
					}
					outBuffer.append((char) value);
				} else {
					if (aChar == 't')
						aChar = '\t';
					else if (aChar == 'r')
						aChar = '\r';
					else if (aChar == 'n')
						aChar = '\n';
					else if (aChar == 'f')
						aChar = '\f';
					outBuffer.append(aChar);
				}
			} else
				outBuffer.append(aChar);
		}
		return outBuffer.toString();
	}

	/**
	 * 删除指定文件夹下的所有文件
	 * 
	 * @param path
	 * @return
	 */
	public static boolean delAllFile(String path) {
		boolean success = false;
		File file = new File(path);
		if (!file.exists()) {
			return success;
		}
		if (!file.isDirectory()) {
			file.delete();
			success = true;
			return success;
		}
		String[] tempList = file.list();
		File temp = null;
		for (int i = 0; i < tempList.length; i++) {
			if (path.endsWith(File.separator)) {
				temp = new File(path + tempList[i]);
			} else {
				temp = new File(path + File.separator + tempList[i]);
			}
			if (temp.isFile()) {
				long lastModeify = temp.lastModified();
				long current = new Date().getTime();
				Log.e("文件创建时间", "current=" + current + "  lastModeify="
						+ lastModeify);
				// 超过3天
				if (current - lastModeify > (1000 * 60 * 60 * 24 * 3)) {
					temp.delete();
				}
			}
			if (temp.isDirectory()) {
				delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
				success = true;
			}
		}
		return success;
	}

	public static class DownloaderTask extends AsyncTask<String, Void, String> {

		private String fileName;

		public DownloaderTask() {

		}

		public DownloaderTask(String fileName) {
			this.fileName = fileName;
		}

		@Override
		protected String doInBackground(String... params) {
			String url = params[0];
			if (fileName == null || fileName.equals("")) {
				fileName = Helper.getReallyFileName(url);
			}
			InputStream input = null;
			try {
				URL fileUrl = new URL(url);
				HttpURLConnection conn = (HttpURLConnection) fileUrl
						.openConnection();
				if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
					// 错误提示
					return null;
				}
				input = conn.getInputStream();

				Helper.writeToDownload(fileName, input);
				return fileName;

			} catch (Exception e) {
				e.printStackTrace();
				return null;
			} finally {
				if (input != null) {
					try {
						input.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if (result == null) {
				Helper.showToast(mContext, "网络异常！\n" + fileName
						+ "下载失败\n请点击重新下载！");
				return;
			}

			Helper.showToast(mContext, result + "\n已保存到 我的->已下载 !");
			// 下载完成后调用第三方打开
			// File directory = new File(Constant.DOWNLOAD_DIRECT);
			// File file = new File(directory, result);
			// Log.i("tag", "Path=" + file.getAbsolutePath());
			// Intent intent = Helper.getFileIntent(file);
			// startActivity(intent);

		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected void onProgressUpdate(Void... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
		}

	}

	public static void uploadHeadIcon(String url, String username,
			File fileName, final PostRecordResponseListener listener) {
		RequestParams requestParams = new RequestParams();

		requestParams.put("uid", username);
		try {
			requestParams.put("fileName", fileName);
		} catch (FileNotFoundException e1) {
			String message = e1.getMessage();
			Log.e("Helper uploadHeadIcon", "message =" + message);
			e1.printStackTrace();
		}

		AsyncHttpServiceHelper.post(url, requestParams,
				new JsonHttpResponseHandler() {
					@Override
					public void onSuccess(int statusCode, Header[] headers,
							JSONObject response) {
						super.onSuccess(statusCode, headers, response);
						try {
							Log.e("Helper uploadHeadIcon", "response ="
									+ response.toString());
							String code = response.getString("code");
							String message = response.getString("message");
							if ("0".equals(code)) {
								if (listener != null) {
									listener.onFinish(message);
								}
							} else {
								if (listener != null) {
									listener.onFailed(message);
								}
							}
						} catch (JSONException e) {
							Log.e("Helper uploadHeadIcon ", "JSONException ="
									+ e.getMessage());
							if (listener != null) {
								listener.onFailed(e.getMessage());
							}
							e.printStackTrace();
						}

					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							String responseString, Throwable throwable) {
						super.onFailure(statusCode, headers, responseString,
								throwable);
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							Throwable throwable, JSONObject errorResponse) {
						super.onFailure(statusCode, headers, throwable,
								errorResponse);
					}
				});

	}

}
